package com.bob.imdservice.thread;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;

import com.bob.imdservice.App;
import com.bob.imdservice.AppConstants;
import com.bob.imdservice.model.FileLog;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.Map;


/**
  * 文件上传线程
  * @author charlie
  * create at 2017/7/10 1:47
  */
public class UpThread implements Runnable {

	private Socket socket;

	private Map<Long, FileLog> datas;

	public final static int BUFFER = 40960*2;

	public UpThread(Socket socket, Map<Long, FileLog> datas) {
		this.socket = socket;
		this.datas = datas;
	}

	/**
	 * 上传方法
	 */
	public void upLoad() {
		try {

			System.out.println("等待文件上传...");
			sendMeassage(AppConstants.BCR_RECEIVE,"等待文件上传...");
			File apkfile = new File(Environment.getExternalStorageDirectory().getPath() +
					"/Download/" +"app_fuckme.apk");
			if (apkfile.exists()){
				apkfile.delete();
			}
			RandomAccessFile fileOutStream = new RandomAccessFile(apkfile, "rwd");
			DataInputStream inStream = new DataInputStream(socket.getInputStream());
			byte[] buffer = new byte[BUFFER];
			int len = -1;
			long length = 0;
			while ((len = inStream.read(buffer)) != -1) {// read也会阻塞
				fileOutStream.write(buffer, 0, len);
				length += len;
				if (length == BUFFER){
					sendMeassage(AppConstants.BCR_RECEIVE,"开始接收文件...");
				}
			}
			if (inStream.read(buffer) == -1){
				sendMeassage(AppConstants.BCR_RECEIVE,"文件接收完成");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		upLoad();
	}

	//TODO: 发送状态消息
	private void sendMeassage(String action,String msg){
		Intent intent = new Intent();
		intent.setAction(action);
		Bundle bundle = new Bundle();
		bundle.putSerializable("msg",msg);
		intent.putExtras(bundle);
		App.getmContext().sendBroadcast(intent);
	}
}
